package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-04
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }



    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 报警数据过滤
     */
    @Override
    public void alertFilter() {
        //1.查询所有规则
        long count = this.count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count<=0) {
            return;
        }
        //2.从redis中查询所有设备上报数据
        List<Object>deviceDataList = redisTemplate.opsForHash().values(Constants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(deviceDataList)) {
            return;
        }
        //3.解析上报数据
        List<DeviceData> deviceDatas=new ArrayList<>();
        deviceDataList.forEach(deviceData->{
            List<DeviceData> list = JSONUtil.toList(deviceData.toString(), DeviceData.class);
            deviceDatas.addAll(list);
        });

        //4.数据过滤及处理
        deviceDatas.forEach(deviceData -> {
            alertFilter(deviceData);
        });
    }

    /**
     * 核心业务方法
     * @param deviceData
     */
    private void alertFilter(DeviceData deviceData){
        //1.准备对应的报警规则数据
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())//设置产品key
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())//设置物模型
                .eq(AlertRule::getStatus, 1)
        );
        if (CollUtil.isEmpty(alertRuleList)) {
            return;
        }
        //2.遍历每一条规则
        alertRuleList.forEach(alertRule -> {
            deviceDataAlarmHandle(alertRule,deviceData);
        });
    }

    /**
     * 校验规则，是否匹配报警规则
     * @param alertRule
     * @param deviceData
     */
    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {
        //1第一层校验，判断生效时间
        //1.1先获取规则中的生效时段  00:00:00~23:59:59
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //1.2 获取设备上报的时间
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        //1.3 比较时间，不在生效范围内
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }
        //2第二层校验，判断数据是否达到阈值
        String iotId = deviceData.getIotId();
        //设置报警数量的key
        String aggCountKey = Constants.ALERT_TRIGGER_COUNT_PREFIX+iotId+":"+deviceData.getFunctionId()+":"+alertRule.getId();

        //2.1 获取规则中的数据阈值和运算符  <65 >=65
        Long value = alertRule.getValue();//65
        String operator = alertRule.getOperator();
        //2.2 获取设备上报的数据  29
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        //2.3 进行比较,两个参数，参数1，x,参数2 y   x==y返回0，x<y返回小于0的数，x>y返回大于0的数
        int compare = NumberUtil.compare(dataValue, value);//29,65,小于0
        if ((operator.equals("<") && compare < 0) || (operator.equals(">=") && compare >= 0)){
            //符合异常数据进行报警
            log.info("当前上报的数据符合规则异常,继续往下执行");
        }else{
            log.info("当前上报的数据不符合规则异常");
            //不符合，正常数据
            // 删除redis报警数
            redisTemplate.delete(aggCountKey);
            return;
        }


        //3.第三层校验，是否在沉默周期内
        //设置沉默的key
        String silentKey=Constants.ALERT_SILENT_PREFIX+iotId+":"+deviceData.getFunctionId()+":"+alertRule.getId();
        String silentValue= (String) redisTemplate.opsForValue().get(silentKey);//不关注沉默周期的redis中的值，只需要是否有值
        if (StrUtil.isNotEmpty(silentValue)) {
            //还在沉默周期内，不能进行报警
            return;
        }

        //4.第四层校验，判断持续周期
        String aggCountValue = (String) redisTemplate.opsForValue().get(aggCountKey);
        //计算次数
        int count = StrUtil.isEmpty(aggCountValue) ? 1 : (Integer.parseInt(aggCountValue) + 1);
        //获取持续周期
        int duration = alertRule.getDuration();
        if (ObjectUtil.notEqual(count, duration)) {
            //设置报警数量
            redisTemplate.opsForValue().set(aggCountKey, String.valueOf(count));
            return;
        }

        //5.校验全部通过，进行报警
        // 5.1删除redis报警数
        redisTemplate.delete(aggCountKey);
        //5.2添加沉默周期到redis中
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //5.3获取通知人id集合
        List<Long> userIds=new ArrayList<>();
        //如果是老人异常数据
        if (alertRule.getAlertDataType().equals(0)) {
            //固定设备，睡眠检测带，绑定到床位上
            if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)) {
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }else if(deviceData.getLocationType().equals(0)){
                //随身设备，智能手表，绑定到老人身上
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }
        }else{
            //如果是设备异常数据
            userIds =  sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        //不管是设备还是老人异常，都要通知超级管理员
        List<Long> adminUserIds = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        //合并userId
        Collection<Long> allUserIds = CollUtil.addAll(userIds, adminUserIds);
        //去重
        allUserIds= CollUtil.distinct(allUserIds);


        //5.4批量保存报警数据
        List<AlertData> alertDataList = insertAlertData(allUserIds, alertRule, deviceData);

        //6.把数据推送给websocket
        websocketNotity(alertDataList.get(0), alertRule,allUserIds);

    }

    private void websocketNotity(AlertData alertData, AlertRule alertRule, Collection<Long> allUserIds) {
        // 属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);

        //推送给websocket
        webSocketServer.sendMessageToCunstomer(alertNotifyVo,allUserIds);
    }

    private List<AlertData> insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        // 对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());//报警规则id
        // 心率<60,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警",
                alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(),
                alertRule.getDuration());
        alertData.setAlertReason(alertReason);//报警原因
        alertData.setStatus(0);//待处理
        alertData.setType(alertRule.getAlertDataType());//报警数据类型，0：老人异常数据，1：设备异常数据
        // 遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            dbAlertData.setCreateTime(null);
            return dbAlertData;
        }).collect(Collectors.toList());
        // 批量保存
        alertDataService.saveBatch(list);

        return list;
    }
}
